function [theta2,deScaling,check,h0Hat,hxHat,What] = Var1_GMM_closedForm(Var_u,Cov10_u,Cov01_u,factors,allowDeSaling)
% This function computes the closed form solution for the VAR(1) model when the factors
% display measurement errors

[dimx, T]            = size(factors);
varUa                = zeros(dimx+1,dimx+1);
cov10Ua              = zeros(dimx+1,dimx+1);
varU                 = sum(Var_u(:,:,1:T-1),3);
cov10U               = sum(Cov10_u(:,:,2:T),3);
cov01U               = sum(Cov01_u(:,:,2:T),3);
varUa(1:dimx,1:dimx) = varU;
cov10Ua(1:dimx,1:dimx)= cov10U;
X                    = [factors(:,1:T-1);  ones(1,T-1)];
Y                    = [factors(:,2:T);    ones(1,T-1)];
haTrans              = (X*X'-varUa)\(X*Y'-cov10Ua);
ha                   = haTrans';
What                 = Y'-X'*haTrans;
hxHat                = ha(1:dimx,1:dimx);
h0Hat                = ha(1:dimx,dimx+1);
omegaHat             = 1/T*(What(:,1:dimx)'*What(:,1:dimx) - varU - hxHat*varU*hxHat'+cov10U*hxHat'+hxHat*cov01U);

deScaling= 1;
[SwHat,check] = chol(omegaHat,'lower');
if allowDeSaling == 1
    idx = 1;
    while check ~= 0 && idx <= 20
        % Reducing deScaling
        deScaling = deScaling*0.99;
        omegaHat = 1/T*(What(:,1:dimx)'*What(:,1:dimx) - varU*deScaling - hxHat*varU*deScaling*hxHat'+cov10U*hxHat'+hxHat*cov01U);
        [SwHat,check] = chol(omegaHat,'lower');
        idx = idx + 1;
    end
    if check ~= 0
        SwHat = NaN(dimx,dimx);
    end
end

% Saving out
theta2 = setTheta2(h0Hat,hxHat,SwHat);
% Deleting the extra column in wHat with zeros.
What   = What(:,1:dimx);

end

